// Netflix数据分析页面修改脚本
(function() {
    'use strict';
    
    let currentChart = null;
    let isNetflixPageInjected = false;
    
    // 等待页面加载完成
    function init() {
        console.log('=== Netflix分析脚本初始化 ===');
        console.log('当前hash:', window.location.hash);
        console.log('当前href:', window.location.href);
        
        // 尝试多次查找并修改"视频属性分析"文本
        let attempts = 0;
        const maxAttempts = 50;
        
        const intervalId = setInterval(function() {
            attempts++;
            
            // 查找所有包含"视频属性分析"的元素
            const elements = document.querySelectorAll('*');
            let found = false;
            
            elements.forEach(function(element) {
                // 只检查文本节点
                if (element.childNodes.length > 0) {
                    element.childNodes.forEach(function(node) {
                        if (node.nodeType === 3 && node.nodeValue && node.nodeValue.trim() === '视频属性分析') {
                            node.nodeValue = '电影数据分析';
                            found = true;
                            console.log('已将"视频属性分析"修改为"电影数据分析"');
                        }
                    });
                }
            });
            
            // 查找侧边栏菜单项
            const menuItems = document.querySelectorAll('.el-submenu__title, .el-menu-item');
            menuItems.forEach(function(item) {
                const text = item.textContent.trim();
                if (text === '视频属性分析' || text === '电影数据分析') {
                    // 修改文本
                    const span = item.querySelector('span');
                    if (span && (span.textContent.trim() === '视频属性分析' || span.textContent.trim() === '电影数据分析')) {
                        span.textContent = '电影数据分析';
                        found = true;
                        console.log('已修改侧边栏菜单项');
                    }
                }
            });
            
            // 如果找到了元素或者达到最大尝试次数，停止循环
            if (found || attempts >= maxAttempts) {
                clearInterval(intervalId);
                if (found) {
                    console.log('Netflix数据分析页面初始化完成');
                }
            }
        }, 200);
        
        // 检查当前路由是否为 /analysis/edit
        checkAndReplaceContent();
    }
    
    // 检查并替换页面内容
    function checkAndReplaceContent() {
        setTimeout(function() {
            const hash = window.location.hash;
            console.log('当前路由hash:', hash);
            
            // 检查面包屑中是否有“视频属性分析”或“电影数据分析”
            const breadcrumb = document.querySelector('.el-breadcrumb');
            if (breadcrumb) {
                const breadcrumbText = breadcrumb.textContent;
                console.log('面包屑文本:', breadcrumbText);
                if (breadcrumbText.indexOf('视频属性分析') > -1 || breadcrumbText.indexOf('电影数据分析') > -1) {
                    console.log('检测到目标页面（通过面包屑），准备替换内容');
                    replacePageContent();
                    return;
                }
            }
            
            // 检查多个可能的路由
            if (hash && (hash.indexOf('/analysis/edit') > -1 || 
                        hash.indexOf('视频属性分析') > -1 || 
                        hash.indexOf('电影数据分析') > -1)) {
                console.log('检测到目标路由，准备替换内容');
                replacePageContent();
            }
        }, 500);
    }
    
    // 替换页面内容为Netflix分析界面
    function replacePageContent() {
        if (isNetflixPageInjected) {
            console.log('已经注入过Netflix页面，跳过');
            return;
        }
        
        console.log('正在查找 .app-container 元素...');
        const appContainer = document.querySelector('.app-container');
        
        if (!appContainer) {
            console.log('未找到 .app-container，500ms后重试...');
            setTimeout(replacePageContent, 500);
            return;
        }
        
        console.log('找到 .app-container，开始注入Netflix分析页面');
        isNetflixPageInjected = true;
        
        // 替换内容
        appContainer.innerHTML = `
            <div class="netflix-analysis-container" style="padding: 20px;">
                <h2 style="text-align: center; margin-bottom: 30px; font-size: 28px; color: #333;">🎬 电影数据分析 - Netflix数据可视化</h2>
                
                <!-- 数据集上传区域 -->
                <div class="upload-section" style="background: white; border-radius: 10px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);">
                    <h3 style="margin-bottom: 15px; color: #333; font-size: 18px;">📁 上传数据集：</h3>
                    <div style="display: flex; align-items: center; gap: 15px;">
                        <input type="file" id="csvFileInput" accept=".csv" style="display: none;">
                        <button id="selectFileBtn" style="padding: 10px 20px; border: 2px dashed #667eea; border-radius: 8px; background: white; color: #667eea; font-size: 14px; cursor: pointer; transition: all 0.3s;">
                            📂 选择CSV文件
                        </button>
                        <span id="fileNameDisplay" style="color: #666; font-size: 14px;">未选择文件</span>
                        <button id="uploadBtn" style="padding: 10px 20px; border: none; border-radius: 8px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 14px; cursor: pointer; transition: all 0.3s; display: none;">
                            ⬆️ 上传并分析
                        </button>
                        <span id="uploadStatus" style="color: #52c41a; font-size: 14px; display: none;">✓ 上传成功</span>
                    </div>
                </div>
                
                <div class="controls" style="background: white; border-radius: 10px; padding: 20px; margin-bottom: 30px; box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);">
                    <h3 style="margin-bottom: 15px; color: #333; font-size: 18px;">选择分析模型：</h3>
                    <div class="model-buttons" style="display: flex; gap: 15px; flex-wrap: wrap;">
                        <button class="model-btn" data-model="yearDistribution" style="padding: 10px 20px; border: none; border-radius: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 14px; cursor: pointer; transition: all 0.3s ease;">📅 年份分布分析</button>
                        <button class="model-btn" data-model="typeDistribution" style="padding: 10px 20px; border: none; border-radius: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 14px; cursor: pointer; transition: all 0.3s ease;">🎭 类型分布分析</button>
                        <button class="model-btn" data-model="countryDistribution" style="padding: 10px 20px; border: none; border-radius: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 14px; cursor: pointer; transition: all 0.3s ease;">🌍 国家分布分析</button>
                        <button class="model-btn" data-model="ratingDistribution" style="padding: 10px 20px; border: none; border-radius: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 14px; cursor: pointer; transition: all 0.3s ease;">⭐ 评级分布分析</button>
                        <button class="model-btn" data-model="genreDistribution" style="padding: 10px 20px; border: none; border-radius: 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-size: 14px; cursor: pointer; transition: all 0.3s ease;">🎪 流派分布分析</button>
                    </div>
                </div>
                
                <div class="chart-container" style="background: white; border-radius: 10px; padding: 30px; box-shadow: 0 2px 12px 0 rgba(0,0,0,.1); min-height: 500px;">
                    <h3 id="chartTitle" style="text-align: center; font-size: 20px; margin-bottom: 20px; color: #333;">请选择一个分析模型</h3>
                    <div id="netflixChart" style="width: 100%; height: 500px;"></div>
                </div>
            </div>
        `;
        
        // 添加按钮点击事件
        const buttons = appContainer.querySelectorAll('.model-btn');
        buttons.forEach(function(btn) {
            btn.addEventListener('click', function() {
                const modelType = this.getAttribute('data-model');
                loadModel(modelType, this);
            });
            
            // 添加鼠标悬停效果
            btn.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px)';
                this.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
            });
            btn.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = 'none';
            });
        });
        
        // 文件选择按钮事件
        const selectFileBtn = document.getElementById('selectFileBtn');
        const fileInput = document.getElementById('csvFileInput');
        const fileNameDisplay = document.getElementById('fileNameDisplay');
        const uploadBtn = document.getElementById('uploadBtn');
        
        selectFileBtn.addEventListener('click', function() {
            fileInput.click();
        });
        
        fileInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                fileNameDisplay.textContent = file.name;
                uploadBtn.style.display = 'inline-block';
            }
        });
        
        uploadBtn.addEventListener('click', function() {
            uploadDataset();
        });
    }
    
    // 上传数据集
    function uploadDataset() {
        const fileInput = document.getElementById('csvFileInput');
        const file = fileInput.files[0];
        
        if (!file) {
            alert('请选择要上传的CSV文件');
            return;
        }
        
        // 检查文件类型
        if (!file.name.endsWith('.csv')) {
            alert('请上传CSV格式的文件');
            return;
        }
        
        const uploadBtn = document.getElementById('uploadBtn');
        const uploadStatus = document.getElementById('uploadStatus');
        const chartTitle = document.getElementById('chartTitle');
        
        // 显示上传中状态
        uploadBtn.disabled = true;
        uploadBtn.textContent = '上传中...';
        chartTitle.innerHTML = '正在上传并处理数据集...';
        
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', file);
        
        // 发送上传请求
        fetch('/api/admin/netflix/upload', {
            method: 'POST',
            body: formData
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.code === 1) {
                // 上传成功，获取字段信息
                const headers = data.response.headers || [];
                
                uploadBtn.style.display = 'none';
                uploadStatus.style.display = 'inline-block';
                uploadStatus.textContent = '✓ 上传成功！数据集已更新';
                
                // 显示可用字段和智能推荐
                showFieldSelector(headers);
                
                // 3秒后隐藏成功提示
                setTimeout(function() {
                    uploadStatus.style.display = 'none';
                }, 3000);
            } else {
                alert('上传失败：' + data.message);
                uploadBtn.disabled = false;
                uploadBtn.textContent = '⬆️ 上传并分析';
                chartTitle.innerHTML = '请选择一个分析模型';
            }
        })
        .catch(function(error) {
            console.error('上传错误:', error);
            alert('上传失败，请检查网络连接');
            uploadBtn.disabled = false;
            uploadBtn.textContent = '⬆️ 上传并分析';
            chartTitle.innerHTML = '请选择一个分析模型';
        });
    }
    
    // 显示字段选择器
    function showFieldSelector(headers) {
        const chartTitle = document.getElementById('chartTitle');
        const modelButtons = document.querySelector('.model-buttons');
        
        if (!headers || headers.length === 0) {
            chartTitle.innerHTML = '数据集上传成功，但未检测到字段信息';
            return;
        }
        
        // 清空现有按钮
        modelButtons.innerHTML = '';
        
        // 智能推荐：根据字段名猜测适合的分析类型
        const fieldSuggestions = smartFieldMapping(headers);
        
        chartTitle.innerHTML = '✅ 数据集已加载！检测到 ' + headers.length + ' 个字段，请选择要分析的字段：';
        
        // 为每个推荐字段创建按钮
        fieldSuggestions.forEach(function(suggestion, index) {
            const colors = [
                'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
                'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
                'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
                'linear-gradient(135deg, #fa709a 0%, #fee140 100%)'
            ];
            
            const btn = document.createElement('button');
            btn.className = 'model-btn';
            btn.setAttribute('data-field', suggestion.field);
            btn.setAttribute('data-chart-type', suggestion.chartType);
            btn.style.cssText = 'padding: 10px 20px; border: none; border-radius: 20px; background: ' + 
                colors[index % colors.length] + '; color: white; font-size: 14px; cursor: pointer; transition: all 0.3s ease;';
            btn.textContent = suggestion.icon + ' ' + suggestion.field;
            
            btn.addEventListener('click', function() {
                const field = this.getAttribute('data-field');
                const chartType = this.getAttribute('data-chart-type');
                loadGenericFieldAnalysis(field, chartType, this);
            });
            
            btn.addEventListener('mouseenter', function() {
                this.style.transform = 'translateY(-2px)';
                this.style.boxShadow = '0 4px 12px rgba(0,0,0,0.15)';
            });
            btn.addEventListener('mouseleave', function() {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = 'none';
            });
            
            modelButtons.appendChild(btn);
        });
        
        // 添加"自定义字段"按钮
        const customBtn = document.createElement('button');
        customBtn.className = 'model-btn';
        customBtn.style.cssText = 'padding: 10px 20px; border: 2px dashed #999; border-radius: 20px; background: white; color: #666; font-size: 14px; cursor: pointer; transition: all 0.3s ease;';
        customBtn.textContent = '🔧 自定义字段分析';
        customBtn.addEventListener('click', function() {
            showCustomFieldDialog(headers);
        });
        modelButtons.appendChild(customBtn);
    }
    
    // 智能字段映射
    function smartFieldMapping(headers) {
        const suggestions = [];
        const headersArray = Array.from(headers);
        
        // 常见字段关键词映射
        const patterns = [
            { keywords: ['year', '年份', '年', 'date', '日期'], icon: '📅', chartType: 'line' },
            { keywords: ['type', '类型', 'category', '分类', 'kind'], icon: '🎭', chartType: 'pie' },
            { keywords: ['country', '国家', 'nation', '地区'], icon: '🌍', chartType: 'bar' },
            { keywords: ['rating', '评级', 'score', '评分', 'level'], icon: '⭐', chartType: 'bar' },
            { keywords: ['genre', '流派', 'style', '风格', 'tag', '标签'], icon: '🎪', chartType: 'bar' },
            { keywords: ['status', '状态', 'state'], icon: '📊', chartType: 'pie' },
            { keywords: ['price', '价格', 'cost', '费用', 'amount'], icon: '💰', chartType: 'bar' }
        ];
        
        headersArray.forEach(function(header) {
            const lowerHeader = header.toLowerCase();
            
            for (let i = 0; i < patterns.length; i++) {
                const pattern = patterns[i];
                for (let j = 0; j < pattern.keywords.length; j++) {
                    if (lowerHeader.includes(pattern.keywords[j])) {
                        suggestions.push({
                            field: header,
                            icon: pattern.icon,
                            chartType: pattern.chartType
                        });
                        return; // 匹配后跳出
                    }
                }
            }
        });
        
        // 如果没有匹配的，取前5个字段
        if (suggestions.length === 0) {
            headersArray.slice(0, 5).forEach(function(header) {
                suggestions.push({
                    field: header,
                    icon: '📊',
                    chartType: 'bar'
                });
            });
        }
        
        return suggestions.slice(0, 6); // 最多显示6个推荐字段
    }
    
    // 初始化图表
    function initChart() {
        const chartDom = document.getElementById('netflixChart');
        if (!chartDom) return null;
        
        if (currentChart) {
            currentChart.dispose();
        }
        currentChart = echarts.init(chartDom);
        return currentChart;
    }
    
    // 通用字段分析
    function loadGenericFieldAnalysis(fieldName, chartType, btnElement) {
        const chart = initChart();
        if (!chart) return;
        
        const chartTitle = document.getElementById('chartTitle');
        chartTitle.innerHTML = '正在加载 ' + fieldName + ' 分析...';
        
        // 移除所有按钮的高亮
        const allBtns = document.querySelectorAll('.model-btn');
        allBtns.forEach(function(btn) {
            btn.style.opacity = '0.6';
        });
        btnElement.style.opacity = '1';
        
        fetch('/api/admin/netflix/analysis/fieldDistribution', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                fieldName: fieldName,
                chartType: chartType,
                topN: '10'
            })
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            if (data.code === 1) {
                const result = data.response;
                chartTitle.innerHTML = result.title;
                
                let option = {};
                
                if (chartType === 'pie') {
                    // 饼图
                    const pieData = result.labels.map(function(label, index) {
                        return { value: result.counts[index], name: label };
                    });
                    
                    option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 10,
                            data: result.labels
                        },
                        series: [{
                            name: fieldName,
                            type: 'pie',
                            radius: '55%',
                            center: ['50%', '60%'],
                            data: pieData,
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }]
                    };
                } else if (chartType === 'line') {
                    // 折线图
                    option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        xAxis: {
                            type: 'category',
                            data: result.labels,
                            axisLabel: {
                                rotate: 45
                            }
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [{
                            data: result.counts,
                            type: 'line',
                            smooth: true,
                            areaStyle: {
                                color: 'rgba(102, 126, 234, 0.3)'
                            },
                            itemStyle: {
                                color: '#667eea'
                            }
                        }]
                    };
                } else {
                    // 柱状图 (默认)
                    option = {
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        xAxis: {
                            type: 'category',
                            data: result.labels,
                            axisLabel: {
                                rotate: 45,
                                interval: 0
                            }
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [{
                            data: result.counts,
                            type: 'bar',
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: '#667eea' },
                                    { offset: 1, color: '#764ba2' }
                                ])
                            }
                        }]
                    };
                }
                
                chart.setOption(option);
            } else {
                chartTitle.innerHTML = '加载失败：' + data.message;
                alert('分析失败：' + data.message);
            }
        })
        .catch(function(error) {
            console.error('请求错误:', error);
            chartTitle.innerHTML = '请求失败';
            alert('请求失败，请检查网络连接');
        });
    }
    
    // 显示自定义字段对话框
    function showCustomFieldDialog(headers) {
        const headersArray = Array.from(headers);
        
        let options = headersArray.map(function(h) {
            return '<option value="' + h + '">' + h + '</option>';
        }).join('');
        
        const dialogHtml = '<div style="padding: 20px;">' +
            '<h4 style="margin-bottom: 15px;">选择要分析的字段：</h4>' +
            '<select id="customFieldSelect" style="width: 100%; padding: 10px; margin-bottom: 15px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">' +
            options +
            '</select>' +
            '<h4 style="margin-bottom: 15px;">选择图表类型：</h4>' +
            '<select id="customChartType" style="width: 100%; padding: 10px; margin-bottom: 20px; border: 1px solid #ddd; border-radius: 5px; font-size: 14px;">' +
            '<option value="bar">柱状图</option>' +
            '<option value="pie">饼图</option>' +
            '<option value="line">折线图</option>' +
            '</select>' +
            '<div style="text-align: right;">' +
            '<button onclick="closeCustomDialog()" style="padding: 8px 20px; margin-right: 10px; border: 1px solid #ddd; border-radius: 5px; background: white; cursor: pointer;">取消</button>' +
            '<button onclick="executeCustomAnalysis()" style="padding: 8px 20px; border: none; border-radius: 5px; background: #667eea; color: white; cursor: pointer;">确定</button>' +
            '</div>' +
            '</div>';
        
        const chartTitle = document.getElementById('chartTitle');
        const chartDiv = document.getElementById('netflixChart');
        
        chartDiv.innerHTML = dialogHtml;
        chartTitle.innerHTML = '🔧 自定义字段分析';
        
        // 将函数挂载到window以便内联事件调用
        window.closeCustomDialog = function() {
            chartDiv.innerHTML = '';
            chartTitle.innerHTML = '请选择一个分析模型';
        };
        
        window.executeCustomAnalysis = function() {
            const field = document.getElementById('customFieldSelect').value;
            const chartType = document.getElementById('customChartType').value;
            
            chartDiv.innerHTML = '';
            loadGenericFieldAnalysis(field, chartType, document.querySelector('.model-btn'));
        };
    }
    
    // 加载模型数据
    function loadModel(modelType, btnElement) {
        const chart = initChart();
        if (!chart) return;
        
        const chartTitle = document.getElementById('chartTitle');
        
        // 更新按钮状态
        document.querySelectorAll('.model-btn').forEach(function(btn) {
            btn.style.background = 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)';
        });
        if (btnElement) {
            btnElement.style.background = 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)';
        }
        
        // 显示加载状态
        chartTitle.innerHTML = '加载中...';
        chart.showLoading();
        
        // API映射
        const apiMap = {
            'yearDistribution': '/api/admin/netflix/analysis/yearDistribution',
            'typeDistribution': '/api/admin/netflix/analysis/typeDistribution',
            'countryDistribution': '/api/admin/netflix/analysis/countryDistribution',
            'ratingDistribution': '/api/admin/netflix/analysis/ratingDistribution',
            'genreDistribution': '/api/admin/netflix/analysis/genreDistribution'
        };
        
        // 调用API
        fetch(apiMap[modelType], {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        })
        .then(function(response) { return response.json(); })
        .then(function(data) {
            chart.hideLoading();
            if (data.code === 1) {
                chartTitle.innerHTML = data.response.title;
                renderChart(chart, modelType, data.response);
            } else {
                chartTitle.innerHTML = '数据加载失败';
                console.error('API错误:', data.message);
            }
        })
        .catch(function(error) {
            chart.hideLoading();
            chartTitle.innerHTML = '数据加载失败';
            console.error('请求失败:', error);
        });
    }
    
    // 渲染图表
    function renderChart(chart, modelType, data) {
        let option = {};
        
        switch(modelType) {
            case 'yearDistribution':
                option = getLineChartOption(data.years, data.counts, '数量');
                break;
            case 'typeDistribution':
                option = getPieChartOption(data.types, data.counts);
                break;
            case 'countryDistribution':
                option = getBarChartOption(data.countries, data.counts, '数量');
                break;
            case 'ratingDistribution':
                option = getPieChartOption(data.ratings, data.counts);
                break;
            case 'genreDistribution':
                option = getBarChartOption(data.genres, data.counts, '数量');
                break;
        }
        
        chart.setOption(option);
        
        // 响应式调整
        window.addEventListener('resize', function() {
            if (currentChart) {
                currentChart.resize();
            }
        });
    }
    
    // 折线图配置
    function getLineChartOption(xData, yData, yAxisName) {
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '10%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: xData,
                axisLabel: {
                    rotate: 45,
                    interval: Math.floor(xData.length / 20)
                }
            },
            yAxis: {
                type: 'value',
                name: yAxisName
            },
            series: [{
                data: yData,
                type: 'line',
                smooth: true,
                lineStyle: {
                    width: 3,
                    color: '#667eea'
                },
                areaStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: 'rgba(102, 126, 234, 0.5)'
                    }, {
                        offset: 1,
                        color: 'rgba(102, 126, 234, 0.1)'
                    }])
                },
                itemStyle: {
                    color: '#667eea'
                }
            }],
            dataZoom: [{
                type: 'inside'
            }, {
                type: 'slider'
            }]
        };
    }
    
    // 饼图配置
    function getPieChartOption(names, values) {
        const data = names.map(function(name, index) {
            return {
                name: name,
                value: values[index]
            };
        });
        
        return {
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [{
                type: 'pie',
                radius: ['40%', '70%'],
                avoidLabelOverlap: true,
                itemStyle: {
                    borderRadius: 10,
                    borderColor: '#fff',
                    borderWidth: 2
                },
                label: {
                    show: true,
                    formatter: '{b}: {d}%'
                },
                emphasis: {
                    label: {
                        show: true,
                        fontSize: '20',
                        fontWeight: 'bold'
                    }
                },
                data: data,
                color: ['#667eea', '#764ba2', '#f093fb', '#f5576c', '#4facfe', 
                        '#00f2fe', '#43e97b', '#38f9d7', '#fa709a', '#fee140']
            }]
        };
    }
    
    // 柱状图配置
    function getBarChartOption(xData, yData, yAxisName) {
        return {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '10%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: xData,
                axisLabel: {
                    rotate: 45,
                    interval: 0
                }
            },
            yAxis: {
                type: 'value',
                name: yAxisName
            },
            series: [{
                data: yData,
                type: 'bar',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                        offset: 0,
                        color: '#667eea'
                    }, {
                        offset: 1,
                        color: '#764ba2'
                    }]),
                    borderRadius: [5, 5, 0, 0]
                },
                emphasis: {
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                            offset: 0,
                            color: '#f093fb'
                        }, {
                            offset: 1,
                            color: '#f5576c'
                        }])
                    }
                }
            }]
        };
    }
    
    // 页面加载完成后初始化
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
    
    // 监听路由变化(Vue Router)
    window.addEventListener('hashchange', function() {
        console.log('hashchange 事件触发, 新hash:', window.location.hash);
        isNetflixPageInjected = false;
        init();
    });
    
    window.addEventListener('popstate', function() {
        console.log('popstate 事件触发');
        isNetflixPageInjected = false;
        init();
    });
    
    // 添加MutationObserver监听DOM变化
    const observer = new MutationObserver(function(mutations) {
        // 检查面包屑中是否有目标文本
        if (!isNetflixPageInjected) {
            const breadcrumb = document.querySelector('.el-breadcrumb');
            if (breadcrumb) {
                const breadcrumbText = breadcrumb.textContent;
                if (breadcrumbText.indexOf('视频属性分析') > -1 || breadcrumbText.indexOf('电影数据分析') > -1) {
                    const appContainer = document.querySelector('.app-container');
                    if (appContainer) {
                        console.log('MutationObserver 检测到目标页面（面包屑），尝试替换内容');
                        replacePageContent();
                    }
                    return;
                }
            }
            
            // 检查是否出现了需要替换的页面
            const hash = window.location.hash;
            if (hash && hash.indexOf('/analysis/edit') > -1) {
                const appContainer = document.querySelector('.app-container');
                if (appContainer) {
                    console.log('MutationObserver 检测到页面变化，尝试替换内容');
                    replacePageContent();
                }
            }
        }
    });
    
    // 监听整个body的变化
    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
    
})();
